package com.chatplus.application.service.wxmp.handler;

import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.domain.entity.account.WechatUserEntity;
import com.chatplus.application.enumeration.WechatUserStatusEnum;
import com.chatplus.application.service.account.UserService;
import com.chatplus.application.service.account.WechatUserService;
import com.chatplus.application.service.wxmp.impl.WeChatMpService;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 扫码事件处理器
 *
 * @author chj
 */
@Service
public class ScanHandler extends AbstractHandler {
    static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(ScanHandler.class);

    public ScanHandler(WeChatMpService weChatMpService,
                       WechatUserService wechatUserService,
                       UserService userService) {
        super(weChatMpService, wechatUserService, userService);
    }

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) {
        String appId = wxMpService.getWxMpConfigStorage().getAppId();
        LOGGER.message("接收到扫码事件").context("OPENID", wxMessage.getFromUser()).context("appId", appId).info();
        try {
            WechatUserEntity weChatUser = handleUser(appId, wxMessage.getFromUser(), WechatUserStatusEnum.FOLLOWED);
            return this.handleKey(weChatUser, wxMessage);
        } catch (Exception e) {
            LOGGER.message("扫码事件处理失败").context("OPENID", wxMessage.getFromUser()).exception(e).error();
        }
        return null;
    }

    /**
     * 事理key事件
     */
    private WxMpXmlOutMessage handleKey(WechatUserEntity weChatUser, WxMpXmlMessage wxMpXmlMessage) {
        return this.handleByEventKey(wxMpXmlMessage.getEventKey(), weChatUser, wxMpXmlMessage);
    }
}
